import { defineStore } from 'pinia';
import * as Cesium from 'cesium';
import Dialog from "@/utils/clickopen/yuecengdialog";
import fubiaoimg from "@/assets/fubiao.svg";
import qianbiaoimg from "@/assets/qianbiao.svg";
import { useScaleStore } from "@/stores/scaleStore";
export const useYuecengStore = defineStore('yueceng', {
  state: () => ({
    viewer: null, // Cesium 视图实例
    yuecengData: {
      qianbiao: [], // 潜标数据单独存储
      fubiao: []    // 浮标数据单独存储
    },
    visibility: {   // 独立控制每种类型的显隐状态
      qianbiao: false, // 潜标显隐状态
      fubiao: false    // 浮标显隐状态
    },
    entities: {      // 按类型分开存储 Entity
      qianbiao: [],  // 潜标实体
      fubiao: []     // 浮标实体
    },
    handler: null,   // 事件处理器
    dialogs: null    // 对话框实例
  }),

  actions: {
    // 设置 Viewer
    setViewer(viewer) {
      this.viewer = viewer;
    },

    // 设置跃层数据（分别设置潜标和浮标数据）
    setYuecengData({ type, data }) {
      if (type === 'qianbiao' || type === 'fubiao') {
        this.yuecengData[type] = data;
      } else {
        console.error('无效的数据类型:', type);
      }
    },

    // 加载指定类型的数据（type: 'qianbiao' 或 'fubiao'）
    loadType(type) {
      try {
        // 先清除该类型现有数据
        this.clearType(type);
        
        // 获取对应类型的数据
        const typeData = this.yuecengData[type];
        
        if (!typeData || typeData.length === 0) {
          console.warn(`没有可用的${type}数据`);
          return;
        }
        
        typeData.forEach(data => {
          const position = Cesium.Cartesian3.fromDegrees(data.lon, data.lat);
          
          // 根据类型设置图标
          const iconUrl = type === 'qianbiao' ? qianbiaoimg : fubiaoimg;
          
          const entity = this.viewer.entities.add({
            position,
            billboard: {
              image: iconUrl,
              width: 32,
              height: 32,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.0, 1.5e7, 0.5),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000000)
            },
            originalData: data
          });
          
          this.entities[type].push(entity); // 按类型存储
        });

        // 只需要初始化一次点击事件
        if (!this.handler) {
          this.setupClickHandler();
        }
      } catch (error) {
        console.error(`加载${type}数据失败:`, error);
        // 重置该类型的显隐状态
        this.visibility[type] = false;
        // 清除可能已经添加的部分实体
        this.clearType(type);
        throw error;
      }
    },

    // 设置点击事件
    setupClickHandler() {
      try {
        this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.handler.setInputAction(click => {
          try {
                const scaleStore = useScaleStore();
                const scale = scaleStore.currentScale || 1;
                // 反向计算坐标
                const adjustedPosition = new Cesium.Cartesian2(
                  click.position.x / scale,
                  click.position.y / scale
                );
            const picked = this.viewer.scene.pick(adjustedPosition);
            if (picked && picked.id) {
              this.showInfo(picked.id.originalData, adjustedPosition);
            }
          } catch (error) {
            console.error('处理点击事件失败:', error);
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      } catch (error) {
        console.error('初始化点击处理器失败:', error);
        this.handler = null;
      }
    },

    // 显示信息窗口
    showInfo(data, clickPos) {
      try {
        const ray = this.viewer.camera.getPickRay(clickPos);
        const cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
        
        // 计算最大深度
        const maxDepth = Math.max(
          data.temp_xia || 0, 
          data.salt_xia || 0,
          ...(data.press || []).map(p => Math.abs(p))
        ) + 100;
        
        const opts = {
          viewer: this.viewer,
          position: { _value: cartesian },
          title: "温盐跃层信息",
          originalData: data || null,
          waterDepth: 1000, // 假设水深为 1000m
        };
        
        if (this.dialogs) this.dialogs.windowClose();
        this.dialogs = new Dialog(opts);
      } catch (error) {
        console.error('显示信息窗口失败:', error);
        if (this.dialogs) this.dialogs.windowClose();
      }
    },

    // 清除指定类型的数据
    clearType(type) {
      try {
        this.entities[type].forEach(entity => {
          this.viewer.entities.remove(entity);
        });
        this.entities[type] = [];
        if (this.dialogs) this.dialogs.windowClose();
        if (this.entities.fubiao.length === 0 && this.entities.qianbiao.length === 0) {
          this.removeClickHandler();
        }
      } catch (error) {
        console.error(`清除${type}数据失败:`, error);
        this.entities[type] = []; // 确保状态被重置
      }
    },

    // 移除点击事件处理器
    removeClickHandler() {
      if (this.handler) {
        try {
          this.handler.destroy();
        } catch (error) {
          console.error('销毁点击处理器失败:', error);
        }
        this.handler = null;
      }
    },

    // 切换指定类型的显隐状态
    toggleVisibility(type) {
      try {
        this.visibility[type] = !this.visibility[type];
        if (this.visibility[type]) {
          this.loadType(type); // 显示
        } else {
          this.clearType(type); // 隐藏
        }
      } catch (error) {
        console.error(`切换${type}显隐状态失败:`, error);
        // 发生错误时重置状态
        this.visibility[type] = false;
        this.clearType(type);
      }
    },

    // 同时切换所有类型
    toggleAll(show) {
      try {
        ['qianbiao', 'fubiao'].forEach(type => {
          this.visibility[type] = show;
          if (show) {
            this.loadType(type);
          } else {
            this.clearType(type);
          }
        });
      } catch (error) {
        console.error('切换所有类型显隐状态失败:', error);
        // 发生错误时重置所有状态
        ['qianbiao', 'fubiao'].forEach(type => {
          this.visibility[type] = false;
          this.clearType(type);
        });
      }
    }
  }
});